package route

import (
	"CDSystem/v2/api"
	"CDSystem/v2/common"
	"CDSystem/v2/views"
	"html/template"
	"log"
	"path/filepath"
	"strings"

	"github.com/gin-contrib/multitemplate"
	"github.com/gin-gonic/gin"
)

type RouteHander struct {
	Engine *gin.Engine
}

var RH RouteHander

func (r *RouteHander) InitRender(rootpath string) {
	route := multitemplate.NewRenderer()
	r.Engine.Static("static", "./static")

	baseFunc := template.FuncMap{
		"date":        common.Date,
		"isODD":       common.IsODD,
		"getNextName": common.GetNextName,
	}
	base := filepath.Join(rootpath, "base.html")
	//log.Println(base)
	pages, err := filepath.Glob(filepath.Join(rootpath, "page/*.html"))
	if err != nil {
		log.Println(err)
		return
	}
	publics, err := filepath.Glob(filepath.Join(rootpath, "public/*.html"))
	if err != nil {
		log.Println(err)
		return
	}
	//log.Println(publics)
	for _, page := range pages {
		rot := strings.Split(strings.ReplaceAll(page, "\\", "/"), "/")
		pagename := strings.TrimSuffix(rot[len(rot)-1], ".html")
		//log.Println(pagename)
		route.AddFromFilesFuncs(pagename, baseFunc, append([]string{base, page}, publics...)...)
	}
	r.Engine.HTMLRender = route
}

func (r *RouteHander) SetHandler() {
	r.Engine.GET("/", views.HTML.Index)
	r.Engine.GET("/CdSeg", views.HTML.CdSeg)
	r.Engine.GET("/PDet", views.HTML.PDet)
	r.Engine.GET("/Sseg", views.HTML.Sseg)
	r.Engine.GET("/Det", views.HTML.Det)

	r.Engine.POST("/api/infer", api.API.InferImage)
	r.Engine.POST("/api/postprocess", api.API.PostProcess)
}
